//
//  WriteHelpViewController.m
//  Cunli
//
//  Created by 湛亚 on 15/6/26.
//  Copyright (c) 2015年 lilubin. All rights reserved.
//

#import "WriteHelpViewController.h"
#import "MyDataService.h"
#import "NSString+MD5.h"
//#import "UIImageView+WebCache.h"
#import "WhoCanSeeViewController.h"

#import "DXMessageToolBar.h"
#import "ConvertToCommonEmoticonsHelper.h"
#import "UIImage+fixOrientation.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import "QBImagePickerController.h"
#import "Utils.h"

#import "Helper.h"
#import "Tweet.h"
#import "MWPhotoBrowser.h"
#import "UIColor+Addition.h"

#import "UIViewExt.h"
#import "HGPhotoWall.h"
#import "MWPhotoBrowser.h"
#import "QBImagePickerController.h"

#define kScreenWidth [UIScreen mainScreen].bounds.size.width
#define kScreenHeight [UIScreen mainScreen].bounds.size.height
#define imgViewTag 300
#define closeBtnTag 500

@interface WriteHelpViewController ()<DXMessageToolBarDelegate, UITableViewDataSource,UITableViewDelegate,DXFaceDelegate,UIActionSheetDelegate,UIImagePickerControllerDelegate,QBImagePickerControllerDelegate,MWPhotoBrowserDelegate,HGPhotoWallDelegate,UITextViewDelegate>{
    
    float picWidth;
    NSArray *choosePlaceArray,*picArray;
    NSInteger lastArrayCount;
    NSMutableArray *imgDataArray,*photos;
    NSString *urlString,*picsUrlString,*willSendText,*plaecHolderString,*responseString;
    MBProgressHUD *hud;
    UIView *picsView;
    UITableView *publishTableView;
}

@property (strong, nonatomic) DXMessageToolBar *chatToolBar;
@property (strong, nonatomic) Tweet *curTweet;
@property (nonatomic, strong) HGPhotoWall *photoWall;

@end

@implementation WriteHelpViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    self.title=self.navTitle;
    self.view.backgroundColor=[UIColor convertHexColorToUIColor:0xf6f6f6];
    
    if ([self.navTitle isEqualToString:@"发布帮忙"]) {
        urlString=@"publish_help2.php";
        responseString=@"publish_help";
        choosePlaceArray=[[NSArray alloc]initWithObjects:@"村里人和家乡人",@"村里人",@"家乡人",nil];
        plaecHolderString=@"找人帮忙...";
    }else{
        urlString=@"publish_topic.php";
        responseString=@"publish_topic";
        choosePlaceArray=[[NSArray alloc]initWithObjects:@"本村",@"本县",@"本市",nil];
        plaecHolderString=@"写话题...";
    }
    
    _curTweet = [Tweet tweetForSend];//存放已选图片url
    imgDataArray=[[NSMutableArray alloc]init];//存放选中图片数组
    photos = [NSMutableArray array];//存放浏览的大图
    self.lastClick=0;//谁能看见范围
    lastArrayCount=0;//选中图片张数
    
    [self createNavButton];
    [self createView];
}

-(void)createNavButton{
    
    UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    leftBtn.frame = CGRectMake(0, 0, 28, 28);
    [leftBtn setImage:[UIImage imageNamed:@"regback01"] forState:UIControlStateNormal];
    leftBtn.contentEdgeInsets = UIEdgeInsetsMake(0, -20, 0, 0);
    [leftBtn addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftBarItem = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
    self.navigationItem.leftBarButtonItem = leftBarItem;
    
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.frame = CGRectMake(0, 0, 60, 30);
    [rightBtn setTitle:@"发送" forState:UIControlStateNormal];
    rightBtn.contentEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -30);
    [rightBtn addTarget:self action:@selector(sendHelp) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightBarItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    self.navigationItem.rightBarButtonItem=rightBarItem;
}

- (DXMessageToolBar *)chatToolBar{
    
    if (_chatToolBar == nil) {
        
        _chatToolBar = [[DXMessageToolBar alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height - [DXMessageToolBar defaultHeight] , kScreenWidth, [DXMessageToolBar defaultHeight])];
        _chatToolBar.isComment=YES;
        _chatToolBar.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleRightMargin;
        _chatToolBar.delegate = self;
        _chatToolBar.alpha=0;
    }
    return _chatToolBar;
}

- (void)didChangeFrameToHeight:(CGFloat)toHeight{
    
    [self.view bringSubviewToFront:_chatToolBar];
}

-(void)createView{
    
    [self.view addSubview:self.chatToolBar];
    
    _chatToolBar.inputTextView.autoresizingMask = UIViewAutoresizingNone;
    _chatToolBar.inputTextView.returnKeyType=UIReturnKeyDefault;
    _chatToolBar.inputTextView.frame=CGRectMake(10,5, kScreenWidth-20, 160);
    _chatToolBar.inputTextView.layer.borderWidth = 0;//设置边框
    _chatToolBar.inputTextView.delegate=self;
    _chatToolBar.inputTextView.placeHolder=plaecHolderString;
    //[_chatToolBar.inputTextView becomeFirstResponder];
    [(DXFaceView *)_chatToolBar.faceView setDelegate:self];
    
    publishTableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight-64) style:UITableViewStyleGrouped];
    publishTableView.dataSource=self;
    publishTableView.delegate=self;
    publishTableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    publishTableView.backgroundColor=[UIColor convertHexColorToUIColor:0xf6f6f6];
    [self.view addSubview:publishTableView];
    
    picWidth=(kScreenWidth-50)/4.0;
    picsView = [[UIView alloc] initWithFrame:CGRectMake(15, 0, kScreenWidth-30, picWidth+10)];
    picsView.userInteractionEnabled = YES;
    picsView.backgroundColor=[UIColor greenColor];
    picsView.clipsToBounds = YES;
    
    _photoWall = [[HGPhotoWall alloc] initWithFrame:CGRectMake(0, 0, 0, 0) andLayoutPhotoType:LayoutTwelfPhotos];
    [_photoWall setPhotos:nil];
    _photoWall.delegate = self;
    [_photoWall setEditModel:YES];
    [picsView addSubview:_photoWall];
}

#pragma mark 添加照片

-(void)addPics{
    
    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@"添加图片" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"从相册中选择", nil];
    sheet.actionSheetStyle = UIActionSheetStyleBlackOpaque;
    [sheet showInView:self.view];
}

#pragma mark -actionSheet代理方法
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if (buttonIndex == 0) {
        
        //拍照
        if (![Helper checkCameraAuthorizationStatus]) {
            return;
        }
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.allowsEditing = NO;//设置可编辑
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:picker animated:YES completion:nil];//进入照相界面
        
    }else if (buttonIndex == 1) {
        //从相册中选择
        if (![Helper checkPhotoLibraryAuthorizationStatus]) {
            return;
        }
        QBImagePickerController *imagePickerController = [[QBImagePickerController alloc] init];
        [imagePickerController.selectedAssetURLs removeAllObjects];
        [imagePickerController.selectedAssetURLs addObjectsFromArray:self.curTweet.selectedAssetURLs];
        imagePickerController.filterType = QBImagePickerControllerFilterTypePhotos;
        imagePickerController.delegate = self;
        imagePickerController.allowsMultipleSelection = YES;
        imagePickerController.maximumNumberOfSelection = 9;
        UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:imagePickerController];
        [self presentViewController:navigationController animated:YES completion:NULL];
    }
}

-(void)goBack{
    
    [hud removeFromSuperview];
    self.curTweet.selectedAssetURLs=nil;
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)sendHelp{
    
    if ([_chatToolBar.inputTextView.text isEqualToString:@""]) {
        
        [self showAlertWithMessage:@"内容不能为空!"];
        return;
    }else{
        
        willSendText = [ConvertToCommonEmoticonsHelper convertToCommonEmoticons:_chatToolBar.inputTextView.text];
        NSLog(@">>>>>>>%@",willSendText);
        [self.view endEditing:YES];
        if (imgDataArray.count<1) {
            [self sendContentWithContent:willSendText];
        }else{
            [self uploadPics];
        }
    }
    
}

#pragma mark 发送

-(void)sendContentWithContent:(NSString *)content{
    
    NSMutableDictionary *CheckParams =[[NSMutableDictionary alloc]init];
    [CheckParams setObject:[Config getOwnUserID] forKey:@"userid"];
    [CheckParams setObject:content forKey:@"content"];
    [CheckParams setObject:[Config getOwnAreaids] forKey:@"areaids"];
    [CheckParams setObject:[NSString stringWithFormat:@"%ld",self.lastClick+1] forKey:@"type"];
    
    if (picsUrlString) {
        [CheckParams setObject:picsUrlString forKey:@"pics"];
    }else{
        [CheckParams setObject:@"http://1.jpg" forKey:@"pics"];
    }
    
    NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:[Config getOwnSession]];
    [CheckParams setObject:resultSign forKey:@"sign"];
    
    [MyDataService requestURL:urlString httpMethod:@"POST" params:CheckParams fileDatas:nil complection:^(id result) {
        
        NSLog(@"%@",result);
        [hud hide:YES];
        
        if ([[result objectForKey:@"response"] isEqualToString:responseString]) {
            
            [Config showHUDWithText:@"发送成功!" andImage:@"done"];
        }else{
            NSString *str=[[result objectForKey:@"error"] objectForKey:@"text"];
            if (str) {
                [self showAlertWithMessage:str];
            }else{
                [self showAlertWithMessage:@"发送失败!"];
            }
        }
        [self.navigationController popViewControllerAnimated:YES];
        self.curTweet.selectedAssetURLs=nil;
    }failureAction:^{
        [self showAlertWithMessage:@"发送失败!"];
        [self.navigationController popViewControllerAnimated:YES];
        self.curTweet.selectedAssetURLs=nil;
    }];
}

#pragma mark 上传图片

-(void)uploadPics{
    
    hud = [Config createHUD];
    hud.mode = 0;
    hud.labelText = @"上传图片中...";
    hud.userInteractionEnabled=NO;
    NSMutableDictionary *CheckParams =[[NSMutableDictionary alloc]init];
    [CheckParams setObject:[Config getOwnUserID] forKey:@"userid"];
    NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:[Config getOwnSession]];
    [CheckParams setObject:resultSign forKey:@"sign"];
    
    NSMutableDictionary *file=[[NSMutableDictionary alloc]init];
    [file setValue:imgDataArray forKey:@"image[]"];
    [MyDataService requestURL:@"upfile_imgs.php" httpMethod:@"POST" params:CheckParams fileDatas:file complection:^(id result) {
        
        //NSLog(@"%@", result);
        [hud hide:YES];
        NSData *data=result;
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"%@", dic);
        
        if ([[dic objectForKey:@"response"] isEqualToString:@"error"]) {
            NSString *errorString=[[dic objectForKey:@"error"] objectForKey:@"text"];
            if (errorString) {
                [self showAlertWithMessage:errorString];
            }else{
                [self showAlertWithMessage:@"图片上传失败!"];
            }
            return ;
        }
        NSDictionary *dataDic=[dic objectForKey:@"date"];
        picArray=[[NSArray alloc]initWithArray:[dataDic objectForKey:@"pics"]];
        
        if (!picArray.count==imgDataArray.count) {
            
            [self showAlertWithMessage:@"图片上传失败!"];
            return ;
        }
        
        for (int i=0; i<picArray.count; i++) {
            
            if (i==0) {
                NSString *picUrlString=[NSString stringWithFormat:@"%@",[picArray objectAtIndex:i]];
                picsUrlString=picUrlString;
            }else{
                NSString *picUrlString=[NSString stringWithFormat:@",%@",[picArray objectAtIndex:i]];
                picsUrlString=[NSString stringWithFormat:@"%@%@",picsUrlString,picUrlString];
            }
        }
        NSLog(@">>>>>>>>>>>>%@",picsUrlString);
        [self sendContentWithContent:willSendText];
    }failureAction:^{
        [hud hide:YES];
        [self showAlertWithMessage:@"图片上传失败!"];
    }];
}

-(void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    //出栈时刷新谁能看见cell
    NSIndexPath *indexPath=[NSIndexPath indexPathForRow:0 inSection:1];
    UITableViewCell *cell = (UITableViewCell *)[publishTableView cellForRowAtIndexPath:indexPath];
    cell.detailTextLabel.text=[choosePlaceArray objectAtIndex:_lastClick];
}

- (void)showAlertWithMessage:(NSString *)message
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:message delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alert show];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - DXFaceDelegate表情代理

- (void)selectedFacialView:(NSString *)str isDelete:(BOOL)isDelete
{
    NSString *chatText = _chatToolBar.inputTextView.text;
    
    if (!isDelete && str.length > 0) {
        _chatToolBar.inputTextView.text = [NSString stringWithFormat:@"%@%@",chatText,str];
    }
    else {
        if (chatText.length >= 2)
        {
            NSString *subStr = [chatText substringFromIndex:chatText.length-2];
            if ([(DXFaceView *)_chatToolBar.faceView stringIsFace:subStr]) {
                _chatToolBar.inputTextView.text = [chatText substringToIndex:chatText.length-2];
                
                return;
            }
        }
        
        if (chatText.length > 0) {
            _chatToolBar.inputTextView.text = [chatText substringToIndex:chatText.length-1];
        }
    }
    
}

- (void)sendFace
{
    
}

#pragma mark - UIImagePickerControllerDelegate完成拍照

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    
    UIImage *pickerImage = [info objectForKey:UIImagePickerControllerOriginalImage];
    ALAssetsLibrary *assetsLibrary = [[ALAssetsLibrary alloc] init];
    
    [assetsLibrary writeImageToSavedPhotosAlbum:[pickerImage CGImage] orientation:(ALAssetOrientation)pickerImage.imageOrientation completionBlock:^(NSURL *assetURL, NSError *error) {
        
        [self.curTweet addASelectedAssetURL:assetURL];
        
        UIImage *tempImgOrientation = [pickerImage fixOrientation];
        
        if (tempImgOrientation.size.width>1024 && tempImgOrientation.size.height>1024) {
            tempImgOrientation = [Utils sizeCompressImageTo1024With:tempImgOrientation];
        }
        
        [self.photoWall addLocalPhoto:tempImgOrientation];
        MWPhoto *photo = [MWPhoto photoWithImage:tempImgOrientation];
        [photos addObject:photo];
        
        NSData *data=UIImageJPEGRepresentation(tempImgOrientation,0.4);
        //判断图片大小确定压缩比例
        if (data.length>1024*1024) {
            data=UIImageJPEGRepresentation(tempImgOrientation,0.2);
        }
        [imgDataArray addObject:data];
        [self reloadPicSectionHeight];
    }];
    
    [picker dismissViewControllerAnimated:YES completion:^{}];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - QBImagePickerControllerDelegate完成图片选择

- (void)qb_imagePickerController:(QBImagePickerController *)imagePickerController didSelectAssets:(NSArray *)assets{
    
    NSMutableArray *selectedAssetURLs = [NSMutableArray new];
    [imagePickerController.selectedAssetURLs enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        [selectedAssetURLs addObject:obj];
    }];
    
    //记录当前选中照片
    self.curTweet.selectedAssetURLs = selectedAssetURLs;
    //移除上次数据
    [photos removeAllObjects];
    [imgDataArray removeAllObjects];
    [_photoWall removeFromSuperview];
    
    _photoWall = [[HGPhotoWall alloc] initWithFrame:CGRectMake(0, 0, 0, 0) andLayoutPhotoType:LayoutTwelfPhotos];
    [_photoWall setPhotos:nil];
    _photoWall.delegate = self;
    //_photoWall.backgroundColor = [UIColor yellowColor];
    [_photoWall setEditModel:YES];
    [picsView addSubview:_photoWall];
    
    for (int i=0; i<assets.count; i++) {
        
        ALAsset *asset=assets[i];
        UIImage *tempImg=[UIImage imageWithCGImage:asset.defaultRepresentation.fullScreenImage];
        
        if (tempImg.size.width>1024 && tempImg.size.height>1024) {
            tempImg = [Utils sizeCompressImageTo1024With:tempImg];
        }
        
        NSData *data=UIImageJPEGRepresentation(tempImg,0.4);
        //判断图片大小确定压缩比例
        if (data.length>1024*1024) {
            data=UIImageJPEGRepresentation(tempImg,0.2);
        }
        [imgDataArray addObject:data];
        
        MWPhoto *photo = [MWPhoto photoWithImage:tempImg];
        [photos addObject:photo];
        [self.photoWall addLocalPhoto:tempImg];
    }
    [self reloadPicSectionHeight];
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)qb_imagePickerControllerDidCancel:(QBImagePickerController *)imagePickerController{
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark 浏览大图

- (void)photoWallPhotoBrowser:(NSUInteger)index{
    
    MWPhotoBrowser *browser = [[MWPhotoBrowser alloc] initWithDelegate:self];
    browser.isScrollerPic=YES;
    [browser setCurrentPhotoIndex:index];
    [self.navigationController pushViewController:browser animated:YES];
}

- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser {
    return photos.count;
}

- (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index {
    if (index < photos.count) {
        return [photos objectAtIndex:index];
    }
    return nil;
}

#pragma - mark HGPhoto Delegate

- (void)photoWallPhotoTaped:(NSUInteger)index{
    
    [imgDataArray removeObjectAtIndex:index];
    [self.photoWall deletePhotoByIndex:index];
    [photos removeObjectAtIndex:index];
    [self.curTweet.selectedAssetURLs removeObjectAtIndex:index];
    [self reloadPicSectionHeight];
}

- (void)photoWallAddAction{
    
    if (imgDataArray.count>8) {
        [self showAlertWithMessage:@"最多选择9张图片!"];
        return;
    }
    [self keyBoardHidden];
    [self addPics];
}

#pragma mark - UITableView代理

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (section==0) {
        return 2;
    }
    return 1;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:nil];
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    
    if (indexPath.section==0) {
        
        if (indexPath.row==0) {
            [cell addSubview:_chatToolBar.inputTextView];
        }else{
            [cell addSubview:picsView];
        }
        
    }else{
        cell.textLabel.text=@"谁能看见";
        cell.detailTextLabel.text=[choosePlaceArray objectAtIndex:0];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row==0&&indexPath.section==0) {
        return 170;
    }else if (indexPath.row==1){
        NSInteger rowCount=(imgDataArray.count+4)/4;
        CGRect oldRect = picsView.frame;
        oldRect.size.height = rowCount*(picWidth+5);
        picsView.frame=oldRect;
        return rowCount*(picWidth+10);
    }else{
        return 40;
    }
}

#pragma mark - 进入选择可见范围界面

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section==1) {
        WhoCanSeeViewController *seeVC=[[WhoCanSeeViewController alloc]init];
        if ([self.navTitle isEqualToString:@"发布帮忙"]) {
            seeVC.type=1;
        }else{
            seeVC.type=2;
        }
        seeVC.currentRange=_lastClick;
        [self.navigationController pushViewController:seeVC animated:YES];
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    [self keyBoardHidden];
}

- (void)textViewDidBeginEditing:(UITextView *)textView{
    
    _chatToolBar.alpha=1;
}

#pragma mark - 结束编辑

-(void)keyBoardHidden{
    
    [self.chatToolBar endEditing:YES];
    [self.view endEditing:YES];
    _chatToolBar.alpha=0;
}

#pragma mark - 根据图片刷新高度

- (void)reloadPicSectionHeight{
    
    NSIndexPath *picsIndexPath = [NSIndexPath indexPathForRow:1 inSection:0];
    [publishTableView reloadRowsAtIndexPaths:@[picsIndexPath] withRowAnimation:UITableViewRowAnimationNone];
}

@end
